package cn.com.xjnt.vas.web.ordering.api;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frameworks.core.web.controller.BaseController;
import com.frameworks.core.web.result.DataResult;
import com.google.common.collect.Lists;

import cn.com.xjnt.vas.manage.domain.entity.Organization;
import cn.com.xjnt.vas.manage.service.OrganizationService;
import cn.com.xjnt.vas.ordering.domain.entity.FoodMenu;
import cn.com.xjnt.vas.ordering.domain.entity.FoodOrder;
import cn.com.xjnt.vas.ordering.domain.entity.User;
import cn.com.xjnt.vas.ordering.domain.vo.FoodOrderVo;
import cn.com.xjnt.vas.ordering.service.FoodMenuService;
import cn.com.xjnt.vas.ordering.service.FoodOrderService;
import cn.com.xjnt.vas.ordering.service.UserService;

/**
 * 类说明：
 * 
 * @author 作者 LUXIN
 * @version 创建时间：2016年5月25日 下午6:41:56
 */
@Controller
@RequestMapping("/api/foodOrder")
public class FoodOrderAPI extends BaseController {
    @Autowired
    private FoodOrderService foodOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private FoodMenuService foodMenuService;
    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private Mapper mapper;

    /**
     * 放入购物车
     * @param json
     * @return
     */
    @RequestMapping(value = "/add", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult add(@RequestBody JSONObject json) {
        DataResult dataRet = new DataResult();
        try {
            String mobile = json.getString("mobile");// 手机号
            Long menuId = json.getLong("menuId");// 菜单id
            Long orgId = json.getLong("orgId");// 组织机构id,前端页面写死

            Organization org = organizationService.findById(orgId);
            if (org == null) {
                dataRet.pushOk("组织机构不存在");
                dataRet.getExtra().put("state", 0);
                return dataRet;
            }
            List<User> users = userService.findByMobile(mobile);
            if (users.size() == 0) {
                dataRet.getExtra().put("state", 0);
                dataRet.pushOk("用户不存在");
                return dataRet;
            }
            FoodMenu foodMenu = foodMenuService.findById(menuId);
            FoodOrder foodOrder = new FoodOrder();

            foodOrder.setUser(users.get(0));// 用户
            foodOrder.setFoodMenu(foodMenu);// 菜单
            foodOrder.setNum(1);// 购买数量
            foodOrder.setOrganization(org);// 所属组织机构
            foodOrder.setType(0);// 草稿状态
            foodOrderService.save(foodOrder);

            dataRet.getExtra().put("state", 1);
            dataRet.pushOk("操作成功");
        } catch (Exception e) {
            dataRet.pushError("加入购物车失败");
            logger.error("加入购物车错误", e);
        }
        return dataRet;
    }

    /**
     * 获得购物车订单列表（我的购物车）
     * @param json
     * @return
     */
    @RequestMapping(value = "/myCart", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult myCart(@RequestBody JSONObject json) {
        DataResult dataRet = new DataResult();
        try {
            String mobile = json.getString("mobile");
            List<User> lists = userService.findByMobile(mobile);
            if (lists.size() > 0) {
                List<FoodOrder> carts = foodOrderService.myCart(lists.get(0), 0);
                List<FoodOrderVo> lvos = Lists.newArrayList();
                for (FoodOrder foodOrder : carts) {
                    FoodOrderVo vo = mapper.map(foodOrder, FoodOrderVo.class);
                    lvos.add(vo);
                }
                if (lvos.size() > 0) {
                    dataRet.getExtra().put("state", 2);
                    dataRet.pushOk("获取成功");
                } else {
                    dataRet.getExtra().put("state", 1);
                    dataRet.pushOk("无相关数据");
                }
                dataRet.setRows(lvos);
            } else {
                dataRet.getExtra().put("state", 0);
                dataRet.pushOk("用户不存在");
            }
        } catch (Exception e) {
            dataRet.pushError("获得购物车订单失败");
            logger.error("获得购物车订单错误", e);
        }
        return dataRet;
    }

    /**
     * 我的订单（除购物车订单外的订单）
     * @param json
     * @return
     */
    @RequestMapping(value = "/myOrder", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult myOrder(@RequestBody JSONObject json) {
        DataResult dataRet = new DataResult();
        try {
            String mobile = json.getString("mobile");
            List<User> lists = userService.findByMobile(mobile);
            if (lists.size() > 0) {
                List<FoodOrder> orders = foodOrderService.myOrder(lists.get(0));
                List<FoodOrderVo> lvos = Lists.newArrayList();
                for (FoodOrder foodOrder : orders) {
                    FoodOrderVo vo = mapper.map(foodOrder, FoodOrderVo.class);
                    lvos.add(vo);
                }
                if (lvos.size() > 0) {
                    dataRet.getExtra().put("state", 2);
                    dataRet.pushOk("获取成功");
                } else {
                    dataRet.getExtra().put("state", 1);
                    dataRet.pushOk("无相关数据");
                }
                dataRet.setRows(lvos);
            } else {
                dataRet.getExtra().put("state", 0);
                dataRet.pushOk("用户不存在");
            }
        } catch (Exception e) {
            dataRet.pushError("获得我的订单失败");
            logger.error("获得我的订单错误", e);
        }
        return dataRet;
    }

    /**
     * 删除购物车订单
     * @param json
     * @return
     */
    @RequestMapping(value = "/del", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult delOrder(@RequestBody JSONObject json) {
        DataResult dataRet = new DataResult();
        try {
            Long orderId = json.getLong("orderId");
            foodOrderService.deleteById(orderId);
            dataRet.pushOk("删除成功");
        } catch (Exception e) {
            dataRet.pushError("删除订单失败");
            logger.error("删除订单错误", e);
        }
        return dataRet;
    }

    /**
     * 结算
     * @param json
     * @return
     */
    @RequestMapping(value = "/pay", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult pay(@RequestBody JSONObject json) {
        DataResult dataRet = new DataResult();
        try {
            JSONArray orders = json.getJSONArray("orders");
            for (Object object : orders) {
                JSONObject order = (JSONObject) object;
                Long orderId = order.getLong("orderId");
                FoodOrder model = foodOrderService.findById(orderId);
                model.setNum(order.getIntValue("num"));
                model.setTotal(
                        model.getFoodMenu().getDiscount().multiply(BigDecimal.valueOf(order.getIntValue("num"))));
                model.setType(1);// 等待商家确认
                model.setOrderTime(new Date());
                foodOrderService.update(model);
            }
            dataRet.pushOk("操作成功");
        } catch (Exception e) {
            dataRet.pushError("订单结算失败");
            logger.error("订单结算错误", e);
        }
        return dataRet;
    }

    /**
     * 修改订单状态
     * @param json
     * @return
     */
    @RequestMapping(value = "/changeType", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult changeType(@RequestBody JSONObject json) {
        DataResult dataRet = new DataResult();
        try {
            int type = json.getIntValue("type");
            Long orderId = json.getLong("orderId");
            
            FoodOrder model = foodOrderService.findById(orderId);
            switch (type) {
            case 3:// 配送中
                Date dispatchTime = json.getDate("dispatchTime");//配送时间
                Date preFinishTime = json.getDate("preFinishTime");//预计到达时间
                model.setDispatchTime(dispatchTime);
                model.setPreFinishTime(preFinishTime);
                break;
            case 4:// 订单已完成
                Date realFinishTime = json.getDate("realFinishTime");
                model.setRealFinishTime(realFinishTime);//实际到达时间
                break;
            case 5:// 取消订单
                String reason = json.getString("reason");
                model.setReason(reason);//取消原因
                break;
            default://1:商家待确认；2：商家确认
                model.setType(type);
                break;
            }
            dataRet.pushOk("操作成功");
            foodOrderService.update(model);
        } catch (Exception e) {
            dataRet.pushError("订单结算失败");
            logger.error("订单结算错误", e);
        }
        return dataRet;
    }
}
